from PySide6.QtWidgets import QApplication, QWidget
from PySide6.QtGui import QDoubleValidator
from ui.unit_conversion_ui import Ui_ConversionForm
from util.math_util import delete_extra_zero


class UnitConversionWindow(QWidget, Ui_ConversionForm):
    def __init__(self):
        super().__init__()
        self.setupUi(self)

        # 定义用于存储数据类型的字典
        self.lengthVar = {'千米': 1000000000000, '米': 1000000000, '分米': 100000000, '厘米': 10000000, '毫米': 1000000,
                          '微米': 1000, '纳米': 1}
        self.massVar = {'千克': 1000000000000000, '克': 10000000000000, '毫克': 10000000, '微克': 1000000, '纳克': 1000,
                        '皮克': 1}
        self.typeDict = {'长度': self.lengthVar, '质量': self.massVar}

        # 初始化下拉框
        self.comboBoxDataType.addItems(self.typeDict.keys())
        self.comboBox1.addItems(self.lengthVar.keys())
        self.comboBox2.addItems(self.lengthVar.keys())

        self.lineEdit1.setValidator(QDoubleValidator())
        self.lineEdit2.setValidator(QDoubleValidator())
        self.bind()

    def bind(self):
        self.comboBoxDataType.currentTextChanged.connect(self.type_change(self.comboBoxDataType.currentText()))
        # textChanged在程序修改值时也会触发，会导致事件多次触发
        self.lineEdit1.textEdited.connect(self.calculate)
        self.lineEdit2.textEdited.connect(self.calculate)
        self.comboBox1.currentTextChanged.connect(self.calculate)
        self.comboBox2.currentTextChanged.connect(self.calculate)

    def calculate(self):
        sender = self.sender()
        if sender == self.lineEdit1 or sender == self.comboBox2:
            text = self.lineEdit1.text()
            if text == '':
                return
            else:
                target_text = float(text) * self.typeDict[self.comboBoxDataType.currentText()][
                    self.comboBox1.currentText()] / self.typeDict[self.comboBoxDataType.currentText()][
                                  self.comboBox2.currentText()]
                print(target_text)
                self.lineEdit2.setText(str(delete_extra_zero(target_text)))
        else:
            text = self.lineEdit2.text()
            if text == '':
                return
            else:
                target_text = float(text) * self.typeDict[self.comboBoxDataType.currentText()][
                    self.comboBox2.currentText()] / self.typeDict[self.comboBoxDataType.currentText()][
                                  self.comboBox1.currentText()]
                print(target_text)
                self.lineEdit1.setText(str(delete_extra_zero(target_text)))

    def type_change(self, text):
        self.comboBox1.clear()
        self.comboBox2.clear()
        self.comboBox1.addItems(self.typeDict[text].keys())
        self.comboBox2.addItems(self.typeDict[text].keys())


if __name__ == '__main__':
    app = QApplication([])
    window = UnitConversionWindow()
    window.show()
    app.exec()
